<script setup>
import { ref, reactive } from 'vue'
import { listDept } from '@/api/system/dept'
import { Search } from '@element-plus/icons-vue'
const { proxy } = getCurrentInstance()
const props = defineProps({
  data: {
    type: Object,
    default: () => {}
  },
  // 关结原因 是否显示
  isClosing: {
    type: Boolean,
    default: false
  },
  // 是否禁用
  db: {
    type: Boolean,
    default: false
  },
  // 单据审核
  examine: {
    type: Boolean,
    default: false
  },
  // 批次到货
  planRelease: {
    type: Boolean,
    default: false
  }
})

// 封装 方法 字典查询
const {
  quality_standard // 质量标准
} = proxy.useDict('quality_standard')

const emit = defineEmits(['cancel', 'submit'])

const ruleFormRef = ref(null)

const selection = ref([])
const deptOptions = ref([])

const TableData = ref([])

const supplierIsShow = ref(false)

// 新增字段
const ruleForm = reactive({
  purchaseContractNo: '', //采购合同编号
  firstBatchTime: '', // 首批到货时间
  endBatchTime: '', // 末批到货时间
  estimatedTime: '', //到货时间
  remark: '', // 备注
  enclosureUrl: '', // 附件
  actualUnitPrice: '', // 实际单价
  actualWeight: '', // 实际数量
  supplierId: '', // 供应商id
  materialList: []
})

if (props.data?.id) {
  for (let key in props.data) {
    ruleForm[key] = props.data[key]
  }
}

const rules = reactive({
  purchaseContractNo: [{ required: true, message: '请填写采购合同编号', trigger: 'burl' }],
  firstBatchTime: [{ required: true, message: '请填写首批到货时间', trigger: 'change' }],
  endBatchTime: [{ required: true, message: '请填写末批到货时间', trigger: 'change' }],
  estimatedTime: [{ required: true, message: '请填写到货时间', trigger: 'change' }],
  enclosureUrl: [{ required: true, message: '请上传附件', trigger: 'change' }],
  supplierName: [{ required: true, message: '请填写供应商', trigger: 'change' }],
  demandDept: [{ required: true, message: '请选择需求部门', trigger: 'change' }],
  reviewComments: [{ required: true, message: '请填写评审意见', trigger: 'burl' }]
})

// 供应商选择
const preservation = val => {
  ruleForm.supplierName = val.supplierName
  ruleForm.supplierId = val.id
  supplierIsShow.value = false
}

// 提交
const submit = () => {
  const startDate = new Date(ruleForm.firstBatchTime)
  const validitData = new Date(ruleForm.endBatchTime)
  const starttime = startDate.getTime() //起始时间戳
  const validittime = validitData.getTime() //结束时间戳

  return new Promise((resolve, reject) => {
    ruleFormRef.value.validate((valid, fields) => {
      if (!valid) {
        resolve(false)
        proxy.Mes('warning', '请填写完整')
        return
      }
      if (Number(starttime) > Number(validittime)) {
        proxy.warningMsg('末批到货时间需要晚于首批到货时间！')
        resolve(false)
        return
      }
      // 校验填写 明细项
      if (!ruleForm.materialList[0].actualWeight) return proxy.warningMsg('请填写实际数量')
      if (!ruleForm.materialList[0].actualUnitPrice) return proxy.warningMsg('请填写实际单价')
      if (!ruleForm.materialList[0].actualWeight || !ruleForm.materialList[0].actualUnitPrice) {
        resolve(false)
        return
      }

      // 赋值
      ruleForm.actualWeight = ruleForm.materialList[0].actualWeight
      ruleForm.actualUnitPrice = ruleForm.materialList[0].actualUnitPrice
      resolve(ruleForm)
    })
  })
}

// 列表选中
const handleSelectionChange = selection => {
  selection.value = selection
}

// 文件
const uploadChange = url => {
  // console.log(url, '==========ruleForm.enclosureUrl')
  ruleForm.enclosureUrl = url
}

//输入实际单价时计算实际单价
const actualCalculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0
  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.taxIncludedPrice = Number(record.actualUnitPrice).toFixed(6)
  } else {
    // 含税单价 = 实际单价 + (实际单价 * 增值税税率)
    record.taxIncludedPrice = (
      Number(record.actualUnitPrice) +
      Number(record.actualUnitPrice) * (taxRate / 100)
    ).toFixed(6)
  }
}

//输入含税单价时计算实际单价
const taxInclCalculate = record => {
  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0
  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.actualUnitPrice = Number(record.taxIncludedPrice).toFixed(6)
  } else {
    // 含税单价/(增值税率/100+1)
    record.actualUnitPrice = (Number(record.taxIncludedPrice) / (1 + taxRate / 100)).toFixed(6)
  }
}

/**
 * 计算-单价输入
 */
const calculate = record => {
  console.log(record.taxIncludedPrice, 'record.taxIncludedPrice含税单价1')
  console.log(record.actualUnitPrice, 'record.actualUnitPrice实际单价1')

  // 处理增值税税率为空或无效的情况，默认为 0
  const taxRate = Number(record.invoiceTaxRate) || 0

  // 如果增值税税率为 0，实际单价和含税单价应当相等
  if (taxRate === 0) {
    // 含税单价 = 实际单价
    record.taxIncludedPrice = Number(record.actualUnitPrice).toFixed(6)
  } else {
    // 含税单价 = 实际单价 + (实际单价 * 增值税税率)
    record.taxIncludedPrice = (
      Number(record.actualUnitPrice) +
      Number(record.actualUnitPrice) * (taxRate / 100)
    ).toFixed(6)
  }

  // // 计算实际单价 =  含税单价 - (含税单价 * 增值税税率)
  // record.actualUnitPrice = (
  //   Number(record.taxIncludedPrice) -
  //   Number(record.taxIncludedPrice) * (taxRate / 100)
  // ).toFixed(6)
  // console.log(record.taxIncludedPrice, 'record.taxIncludedPrice含税单价2')
  // console.log(record.actualUnitPrice, 'record.actualUnitPrice实际单价2')
}

function handleAdd(row) {
  listDept().then(response => {
    deptOptions.value = proxy.handleTree(response.data, 'deptId')
  })
  if (row != undefined) {
    ruleForm.demandDept = row.deptId
  }
}
handleAdd()
defineExpose({ submit })
</script>

<template>
  <div class="app-container">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-position="right"
      inline
      scroll-to-error
      label-width="120px"
    >
      <!-- <el-form-item label="采购订单号" prop="purchaseOrderNo">
        <el-input clearable disabled v-model="ruleForm.purchaseOrderNo" />
      </el-form-item> -->
      <el-form-item label="采购合同编号">
        <el-input clearable :disabled="props.db" v-model="ruleForm.purchaseContractNo" />
      </el-form-item>
      <el-form-item label="供应商信息" prop="supplierName">
        <el-input clearable :disabled="props.db" @click="supplierIsShow = true" v-model="ruleForm.supplierName" />
      </el-form-item>
      <el-form-item label="首批到货时间" v-if="!props.planRelease">
        <el-date-picker
          v-model="ruleForm.firstBatchTime"
          :disabled="props.db"
          type="datetime"
          placeholder="请选择时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <el-form-item label="末批到货时间" v-if="!props.planRelease">
        <el-date-picker
          :disabled="props.db"
          v-model="ruleForm.endBatchTime"
          type="datetime"
          placeholder="请选择时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <el-form-item label="预计到货时间" prop="estimatedTime" v-if="props.planRelease">
        <el-date-picker
          v-model="ruleForm.estimatedTime"
          type="datetime"
          placeholder="请选择时间"
          format="YYYY/MM/DD hh:mm:ss"
          value-format="YYYY-MM-DD hh:mm:ss"
        />
      </el-form-item>
      <div class="rk">
        <el-form-item label="备注" prop="remark">
          <el-input
            clearable
            :disabled="props.db"
            v-model="ruleForm.remark"
            :rows="3"
            type="textarea"
            placeholder="请输入备注"
            :input-style="{ width: '100%' }"
          />
        </el-form-item>
      </div>

      <div>
        <el-form-item label="上传附件">
          <FileUpload v-model="ruleForm.enclosureUrl" v-if="!props.db" />
          <DownloadFile :fileList="ruleForm.enclosureUrl" v-else />
        </el-form-item>
      </div>

      <div class="rk">
        <el-form-item label="关结原因" prop="closeReason" v-if="props.isClosing && ruleForm.closeReason">
          <div>
            <span>{{ ruleForm.closeBy }}:&emsp;</span>
            <span>{{ ruleForm.closeReason }}</span>
          </div>
        </el-form-item>
      </div>
      <div class="rk">
        <el-form-item label="评审意见" v-if="props.examine">
          <el-input
            clearable
            v-model="ruleForm.reviewComments"
            :rows="3"
            type="textarea"
            placeholder="请输入评审意见"
            :input-style="{ width: '100%' }"
          />
        </el-form-item>
      </div>
    </el-form>
    <!-- 表格数据 -->
    <el-table
      v-loading="loading"
      stripe
      border
      :data="ruleForm.materialList"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="序号" width="70" type="index" />
      <el-table-column label="物料编码" prop="materialCode" width="auto" />
      <el-table-column label="物料名称" prop="materialName" width="auto" />
      <el-table-column label="单位" prop="unitDict" width="auto" />
      <el-table-column label="下达数量" prop="lowerWeight" width="auto" />
      <el-table-column label="实际数量" width="120">
        <template #default="scope">
          <el-input v-model="scope.row.actualWeight" clearable :disabled="props.db"></el-input>
        </template>
      </el-table-column>
      <el-table-column label="计划单价" prop="plannedUnitPrice" width="auto" />

      <el-table-column label="到货数量" width="120">
        <template #default="scope">
          <el-input
            type="number"
            oninput="if(value<=0)value=''"
            v-model="scope.row.quantityArrivalTimeWeight"
            clearable
            disabled
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="实际单价" width="220">
        <template #default="scope">
          <el-input
            type="number"
            oninput="if(value<=0)value=''"
            v-model="scope.row.actualUnitPrice"
            clearable
            @change="actualCalculate(scope.row)"
            :disabled="props.db"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="含税单价" prop="taxIncludedPrice" width="220">
        <template #default="scope">
          <el-input
            type="number"
            v-model="scope.row.taxIncludedPrice"
            :min="0"
            clearable
            :disabled="props.db"
            @change="taxInclCalculate(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="增值税税率" prop="invoiceTaxRate" width="220">
        <template #default="scope">
          <el-input
            type="number"
            v-model="scope.row.invoiceTaxRate"
            :min="0"
            :disabled="props.db"
            clearable
            @change="calculate(scope.row)"
          />
        </template>
      </el-table-column>
    </el-table>
    <Supplier :is-show="supplierIsShow" @preservation="preservation" @cancel="supplierIsShow = false" />
  </div>
</template>

<style lang="scss" scoped>
.btn {
  margin-top: 20px;
}

.rk ::v-deep .el-form-item {
  width: 100% !important;
}
</style>
